<template>
  <div class="main">
    <div class="form">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="link" @click="goRegister()">
      <el-link type="info">没有账号？去注册吧</el-link>
    </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import url from "@/serviceAPI.config.js";
import { Toast } from "vant";
import decode from "jwt-decode";
export default {
  name: "Register",
  data() {
      var validatePass = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('用户名长度不能小于6位'));
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码长度不能小于6位'));
        }else {
          callback();
        }
      };
      return {
        ruleForm: {
          name: '',
          pass: '',
        },
        rules: {
          name: [
            { validator: validatePass, trigger: 'blur' }
          ],
          pass: [
            { validator: validatePass2, trigger: 'blur' }
          ]
        }
      };
  },
  created() {
  },
  methods: {
    goRegister(){
      this.$router.push("/register");
    },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 表单检验成功 可以登录
            this.axiosLoginUser();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    goBack() {
      this.$router.go(-1);
    },
    // 用户登陆
    axiosLoginUser() {
      this.openLoading = true;
      axios({
        url: url.loginUser,
        method: "post",
        data: {
          userName: this.ruleForm.name,
          passWord: this.ruleForm.pass
        }
      })
        .then(res => {
          console.log(res);
          if (res.data.code === 200 && res.data.message === true) {
            new Promise(resolve => {
              const token = res.data.token;
              localStorage.DStoken = token;
              const user = decode(token);
              localStorage.DSuser = JSON.stringify(user);
              console.log(user);
              // 存储用户信息和 token
              this.$store.commit("getDStoken", token);
              this.$store.commit("getDSUser", user);
              // 设置一个定时器 确保登录状态存储成功之后再显示登录成功
              setTimeout(() => {
                resolve();
              }, 500);
            })
              .then(() => {
                this.$message.success("登录成功");
                this.$router.push("/");
              })
              .catch(err => {
                this.$message.error("登录失败，请尝试再次登录");
                console.log(err);
              });
          } else if (
            res.data.code === 200 &&
            res.data.message === "用户名不存在"
          ) {
            this.$message.error(res.data.message);
            this.openLoading = false;
          } else {
            this.$message.error("密码错误");
            this.openLoading = false;
          }
        })
        .catch(err => {
          console.log(err);
          this.$message.error("登录失败，可能是网络出问题了");
        });
    },
  }
};
</script>

<style scoped>
.main {
  height: 752px;
  width: 100%;
  background: url("../../assets/image/loginBG.jpg");
  background-size: cover;
  background-color: red;
}
.form {
  width: 300px;
  height: 200px;
  position: absolute;
  right: 200px;
  top: 200px;
  background-color: #fff;
  padding-right: 56px;
  padding-top: 42px;
  border-radius: 10px;
}
.register-panel {
  width: 300px;
  border-radius: 0.3rem;
  margin: 300px auto;
}
.register div {
  border-radius: 5rem;
}
.register-botton {
  padding-top: 0.9rem;
}
.link {
  position: absolute;
  left: 217px;
  bottom: 10px;
}
</style>
